import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'
// 如何得到路由实例  createRouter()
// 如何设置路由模式 history
// history 模式   createWebHistory()
// hash 模式      createWebHash()
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

//取消转圈圈
NProgress.configure({
  showSpinner: false,
})

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('@/views/Login/LoginIndex.vue'),
      meta: { title: '登录' },
    },
    {
      path: '/user/patient',
      component: () => import('@/views/User/PatientPage.vue'),
      meta: { title: '家庭档案' },
    },
    {
      path: '/consult/fast',
      component: () => import('@/views/Consult/ConsultFast.vue'),
      meta: { title: '极速问诊' },
    },
    {
      path: '/consult/dep',
      component: () => import('@/views/Consult/ConsultDep.vue'),
      meta: { title: '选择科室' },
    },
    {
      path: '/consult/illness',
      component: () => import('@/views/Consult/ConsultIllness.vue'),
      meta: { title: '病情描述' },
    },
    {
      path: '/consult/pay',
      component: () => import('@/views/Consult/ConsultPay.vue'),
      meta: { title: '问诊支付' },
    },
    {
      path: '/room',
      component: () => import('@/views/Room/RoomIndex.vue'),
      meta: { title: '问诊室' },
      // 加一个导航守卫   beforeEnter
      beforeEnter(to) {
        if (to.query.payResult === 'false') return '/user/consult'
      },
    },
    {
      path: '/login/callback',
      component: () => import('@/views/Login/LoginCallback.vue'),
      meta: { title: '三方登录' },
    },
    {
      path: '/',
      redirect: '/home',
      component: () => import('@/views/Layout/LayoutIndex.vue'),
      children: [
        {
          path: '/home',
          component: () => import('@/views/Home/HomeIndex.vue'),
          meta: { title: '首页' },
        },
        {
          path: '/article',
          component: () => import('@/views/Article/ArticleIndex.vue'),
          meta: { title: '健康百科' },
        },
        {
          path: '/notify',
          component: () => import('@/views/Notify/NotifyIndex.vue'),
          meta: { title: '消息通知' },
        },
        {
          path: '/user',
          component: () => import('@/views/User/UserIndex.vue'),
          meta: { title: '我的' },
        },
      ],
    },
  ],
})

//全局前置守卫：访问权限判断
router.beforeEach(to => {
  NProgress.start()
  //获取token
  const store = useUserStore()
  //白名单
  const wihteList = ['/login', '/login/callback']
  //条件判断  // 如果没有登录且不在白名单内，去登录
  if (!store.user?.token && !wihteList.includes(to.path)) return '/login'
})

//全局后置导航
router.afterEach(to => {
  document.title = `${to.meta.title || ''}-${import.meta.env.VITE_APP_TITLE}`
  NProgress.done()
})
export default router
